package cn.enneagon.kudu;

import java.sql.*;

public class Contants {
    private static String JDBC_DRIVER = "com.cloudera.impala.jdbc41.Driver";
    private static String CONNECTION_URL = "jdbc:impala://cdh001:21050/kudu_test;auth=noSasl";

    static Connection conn = null;

    static PreparedStatement ps = null;

    static ResultSet rs = null;

    public static Connection getConn() {
        if (conn == null) {
            try {
                Class.forName(JDBC_DRIVER);
                conn = DriverManager.getConnection(CONNECTION_URL);
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            }
        }

        return conn;
    }

    public static void createTable() {
        conn = getConn();
        String sql = "CREATE TABLE impala_kudu_test" +
                "(" +
                "companyId BIGINT," +
                "workId BIGINT," +
                "name STRING," +
                "gender STRING," +
                "photo STRING," +
                "PRIMARY KEY(companyId)" +
                ")" +
                "PARTITION BY HASH PARTITIONS 16 " +
                "STORED AS KUDU " +
                "TBLPROPERTIES (" +
                "'kudu.master_address' = 'cdh001:7051,cdh002:7051,cdh003:7051'" +
                ");";

        try {
            ps = conn.prepareStatement(sql);
            ps.execute();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void insertRows(Person person) {
        conn = getConn();
        String sql = "insert into table impala_kudu_test(companyId, workId, name, gender, photo) values(?, ?, ?, ?, ?)";

        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1, person.getCompanyId());
            ps.setInt(2, person.getWorkId());
            ps.setString(3, person.getName());
            ps.setString(4, person.getGender());
            ps.setString(5, person.getPhoto());
            ps.execute();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

    public static ResultSet queryRows() {
        try {
            String sql = "select * from impala_kudu_test";
            ps = getConn().prepareStatement(sql);
            rs = ps.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rs;
    }

    public static void printRows(ResultSet rs) throws SQLException {
        while(rs.next()){
            System.out.println(rs.getString("name") + rs.getString("gender"));
        }
    }
}
